package com.yuke.cloud.service.wmc.controller.frontend;


import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.opc.service.OpcGaodeFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.GroupInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.api.wmc.exceptions.WmcBizException;
import com.yuke.cloud.service.wmc.dto.WmsWarehouseDto;
import com.yuke.cloud.service.wmc.entity.*;
import com.yuke.cloud.service.wmc.service.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by zys on 2018/10/22.
 */

@Slf4j
@RestController
@RequestMapping("/wms/warehouse")
public class WmsWarehouseController extends BaseController {
    @Resource
    private WmsWarehouseService wmsWarehouseService;
    @Resource
    private WmsWarehouseShopService wmsWarehouseShopService;
    @Resource
    private WmsPrinterService wmsPrinterService;
    @Resource
    private WmsWarehouseGroupService wmsWarehouseGroupService;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private WmsStorageService wmsStorageService;
    @Resource
    private DicRegionService dicRegionService;
    @Resource
    private OpcGaodeFeignApi opcGaodeFeignApi;
    @Resource
    private UacUserFeignApi uacUserFeignApi;

    /**
     * 店铺与仓库之间的最大关联距离，单位米
     */
    @Value("${yuke.warehouse.max-distance}")
    private Long maxDistance;


    @GetMapping("/justtest")
    public void justdoit() {
        List<Long> list1 = new ArrayList<>();
        list1.add(Long.valueOf("11"));
        list1.add(Long.valueOf("11"));
        list1.add(Long.valueOf("12"));
        List<Map> warehouseName = wmsWarehouseShopService.getWarehouseNamebyShopId(list1);
        System.out.println(warehouseName);
    }


    @RequestMapping(value = "/book", method = RequestMethod.POST)
    public Wrapper preadd(@RequestParam("name") String name) {
        JSONArray jsonArray = JSONArray.parseArray(name);
        System.err.println("进入wmc系统");
        for (int i = 0; i < jsonArray.size(); i++) {
            Map jsonObject = jsonArray.getJSONObject(i);
            Object shopId = jsonObject.get("shopId");
            Object specId = jsonObject.get("specId");
            Object goodsNum = jsonObject.get("goodsNum");

            Object isFactory = jsonObject.get("isFactory");
            if (PublicUtil.isNotEmpty(isFactory) && Boolean.valueOf(isFactory.toString())) {
                Long warehouseId = 0L;
                wmsWarehouseService.bookgoods(warehouseId, Long.valueOf(specId.toString()), Integer.valueOf(goodsNum.toString()));
            } else {
                // mod by wg 20190727
                Long warehouseId = null;
                if (jsonObject.get("warehouseId") != null) {
                    warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
                }

                if (warehouseId == null || warehouseId <= 0L) {
                    //根据商品id查找店铺id
                    Long aLong = Long.valueOf(shopId.toString());
                    WmsWarehouseShop wmsWarehouseShop = new WmsWarehouseShop();
                    wmsWarehouseShop.setShopId(aLong);
                    List<WmsWarehouseShop> select = wmsWarehouseShopService.select(wmsWarehouseShop);
                    warehouseId = select.get(0).getWarehouseId();
                }

                wmsWarehouseService.bookgoods(warehouseId, Long.valueOf(specId.toString()), Integer.valueOf(goodsNum.toString()));
            }

            System.out.println("仓库预定商品成功");
        }
        return WrapMapper.ok("ok");
    }



    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "wmsWarehouse", value = "该数据记录的POJO") @RequestBody WmsWarehouse wmsWarehouse) {
        Example example = new Example(DicRegion.class);
        Example.Criteria criteria = example.createCriteria();
        List list = new ArrayList();
        list.add(wmsWarehouse.getRegionProvinceId());
        list.add(wmsWarehouse.getRegionCityId());
        list.add(wmsWarehouse.getRegionCountyId());
        criteria.andIn("regionId", list);
        List<DicRegion> dicRegions = dicRegionService.selectByExample(example);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < dicRegions.size(); i++) {
            sb.append(dicRegions.get(i).getRegionName());
        }
        sb.append(wmsWarehouse.getAddress());
        Wrapper<Map> lonLarByAddr = opcGaodeFeignApi.getLonLarByAddr(sb.toString(), dicRegions.get(1).getRegionName());

        if (lonLarByAddr.error()) {
            throw new WmcBizException(ErrorCodeEnum.GL99990002);
        }
        if (lonLarByAddr.getResult() == null) {
            log.info("param:addr={}, city={}, lonLarByAddr={}", sb.toString(), dicRegions.get(1).getRegionName(), lonLarByAddr);
            return WrapMapper.error("无法获取仓库位置信息");
        }
        Iterator<Map.Entry> iter = lonLarByAddr.getResult().entrySet().iterator();
        String addrInfo = "";
        while (iter.hasNext()) {
            addrInfo = iter.next().getValue().toString();
        }
        if (addrInfo == "") {
            log.info("param:addr={}, city={}, lonLarByAddr={}", sb.toString(), dicRegions.get(1).getRegionName(), lonLarByAddr);
            return WrapMapper.error("无法获取仓库位置信息");
        }
        List<Double> location = Arrays.asList(addrInfo.split(",")).stream().map(l -> Double.parseDouble(l)).collect(Collectors.toList());
        wmsWarehouse.setLongitude(new BigDecimal(location.get(0)));
        wmsWarehouse.setLatitude(new BigDecimal(location.get(1)));
        wmsWarehouseService.save(wmsWarehouse);
        WmsWarehouseGroup wmsWarehouseGroup = new WmsWarehouseGroup();
        wmsWarehouseGroup.setWarehouseId(wmsWarehouse.getWarehouseId());
        wmsWarehouseGroup.setGroupId(wmsWarehouse.getGroupId());
        wmsWarehouseGroupService.save(wmsWarehouseGroup);
        return WrapMapper.ok(wmsWarehouse);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        wmsWarehouseService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "wmsWarehouse", value = "需要修改的内容") @RequestBody WmsWarehouse wmsWarehouse) {
        Byte runStatus = wmsWarehouse.getRunStatus();
        if (runStatus.toString().equals("2")) {
            WmsWarehouseShop wmsWarehouseShop = new WmsWarehouseShop();
            wmsWarehouseShop.setWarehouseId(wmsWarehouse.getWarehouseId());
            int size = wmsWarehouseShopService.select(wmsWarehouseShop).size();
            WmsStorage wmsStorage = new WmsStorage();
            wmsStorage.setWarehouseId(wmsWarehouse.getWarehouseId());
            List<WmsStorage> select = wmsStorageService.select(wmsStorage);
            boolean flag = true;
            for (int i = 0; i < select.size(); i++) {
                Integer number = select.get(i).getNumber();
                if (number.intValue() != 0) {
                    flag = false;
                    break;
                }
            }

            if (size == 0 && flag) {
                wmsWarehouseService.update(wmsWarehouse);
                WmsWarehouseGroup wmsWarehouseGroup = new WmsWarehouseGroup();
                wmsWarehouseGroup.setWarehouseId(wmsWarehouse.getWarehouseId());
                WmsWarehouseGroup wmsWarehouseGroup1 = wmsWarehouseGroupService.select(wmsWarehouseGroup).get(0);
                wmsWarehouseGroup1.setGroupId(wmsWarehouse.getGroupId());
                wmsWarehouseGroupService.update(wmsWarehouseGroup1);
                return WrapMapper.ok(wmsWarehouse);
            } else {
                return WrapMapper.error(ErrorCodeEnum.WMC100500017.msg());
            }

        } else {

            wmsWarehouseService.update(wmsWarehouse);
            WmsWarehouseGroup wmsWarehouseGroup = new WmsWarehouseGroup();
            wmsWarehouseGroup.setWarehouseId(wmsWarehouse.getWarehouseId());
            WmsWarehouseGroup wmsWarehouseGroup1 = wmsWarehouseGroupService.select(wmsWarehouseGroup).get(0);
            wmsWarehouseGroup1.setGroupId(wmsWarehouse.getGroupId());
            wmsWarehouseGroupService.update(wmsWarehouseGroup1);
            return WrapMapper.ok(wmsWarehouse);
        }


    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<WmsWarehouse> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        WmsWarehouse wmsWarehouse = wmsWarehouseService.findById(id);
        return WrapMapper.ok(wmsWarehouse);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                  @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Map> list = wmsWarehouseService.finditall1();
        List<Map> list2 = wmsWarehouseService.finditall12();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("regionProvinceName", list2.get(i).get("province"));
            list.get(i).put("regionCityName", list2.get(i).get("city"));
            list.get(i).put("regionCountyName", list2.get(i).get("county"));
        }
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @GetMapping("/getaddress")
    @ApiOperation(httpMethod = "GET", value = "获取省市区信息")
    public Wrapper getit(@ApiParam(name = "id", value = "组织id") @RequestParam(defaultValue = "1") String id,
                         @ApiParam(name = "type", value = "类型") @RequestParam(defaultValue = "1") int type) {
        WmsWarehouse wmsWarehouse = new WmsWarehouse();
        wmsWarehouse.setWarehouseId(Long.valueOf(id));
        wmsWarehouse.setRunStatus((byte) type);
        List<Map> list = wmsPrinterService.getit(wmsWarehouse);
        return WrapMapper.ok(list);
    }

    @GetMapping("/search")
    @ApiOperation(httpMethod = "GET", value = "根据仓库名称获取仓库信息，模糊搜索")
    public Wrapper search(@ApiParam(name = "name", value = "仓库名称") @RequestParam String name) {
        System.out.println(name);
        Example example = new Example(WmsWarehouse.class);
        example.setOrderByClause("create_time desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("warehouseName", "%" + name + "%");
        List<WmsWarehouse> wmsWarehouses = wmsWarehouseService.selectByExample(example);
        return WrapMapper.ok(wmsWarehouses);

    }

    @GetMapping("/getalladdress")
    @ApiOperation(httpMethod = "GET", value = "获取省市区信息")
    public Wrapper getit2(@ApiParam(name = "id", value = "组织id") @RequestParam(defaultValue = "1") String id,
                          @ApiParam(name = "type", value = "类型") @RequestParam(defaultValue = "1") Integer type) {
        WmsWarehouse wmsWarehouse = new WmsWarehouse();
        wmsWarehouse.setWarehouseId(Long.valueOf(id));
        wmsWarehouse.setRunStatus((byte) type.intValue());
        List<Map> list = wmsPrinterService.getit2(wmsWarehouse);
        return WrapMapper.ok(list);
    }

    //仓库名称是否唯一
    @GetMapping("/ifunique")
    public Wrapper ifunique(@ApiParam(name = "warehouseName", value = "组织id") @Param("warehouseName") String warehouseName,
                            @ApiParam(name = "warehouseId", value = "组织id") @Param("warehouseId") Long warehouseId
    ) {
        Example example = new Example(WmsWarehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("warehouseName", warehouseName);

        if (warehouseId != null) {
            criteria.andNotEqualTo("warehouseId", warehouseId);
            List<WmsWarehouse> select = wmsWarehouseService.selectByExample(example);
            if (select.size() >= 1) {
                return WrapMapper.ok("no");
            } else {
                return WrapMapper.ok("yes");
            }
        }
        List<WmsWarehouse> select = wmsWarehouseService.selectByExample(example);
        if (select.size() >= 1) {
            return WrapMapper.ok("no");
        } else {
            return WrapMapper.ok("yes");
        }

    }

    //组织是否可用
    @GetMapping("/groupIdAndNameifunique")
    public Wrapper ifunique2(
            @ApiParam(name = "groupId", value = "groupId") @Param("groupId") Long groupId,
            @ApiParam(name = "warehouseId", value = "warehouseId") @Param("warehouseId") Long warehouseId
    ) {
        Example example = new Example(WmsWarehouseGroup.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("groupId", groupId);
        if (warehouseId != null) {
            criteria.andNotEqualTo("warehouseId", warehouseId);
            int size1 = wmsWarehouseGroupService.selectByExample(example).size();
            if (size1 == 1) {
                return WrapMapper.ok("no");
            } else {
                return WrapMapper.ok("yes");
            }
        }
        int size1 = wmsWarehouseGroupService.selectByExample(example).size();
        if (size1 == 1) {
            return WrapMapper.ok("no");
        } else {
            return WrapMapper.ok("yes");
        }

    }

    //查看详情
    @GetMapping("/getdetail")
    public Wrapper getdetail(@ApiParam(name = "warehouseId", value = "记录id") @RequestParam(defaultValue = "0") Long warehouseId,
                             @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                             @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size


    ) {
        PageHelper.startPage(page, size);
        WmsWarehouseShop wmsWarehouseShop = new WmsWarehouseShop();
        wmsWarehouseShop.setWarehouseId(warehouseId);
        List<WmsWarehouseShop> select = wmsWarehouseShopService.select(wmsWarehouseShop);
        if (select.size() == 0) {
            // mod by wg 20190503 如果没有数据则返回空的列表
//            return WrapMapper.error();
            PageInfo pageInfo = new PageInfo(select);
            pageInfo.setList(select);
            return WrapMapper.ok(pageInfo);
        }
        List<Long> list = new ArrayList<>();
        for (WmsWarehouseShop wm : select) {
            if (wm.getShopId() != null && !wm.getShopId().equals("")) {
                list.add(wm.getShopId());
            }
        }
        //todo 调用feign返回的数据，参数是list。
        List<ShopInfoDto> shopInfoByShopIds = smcFeignApi.getShopInfoByShopIds(list);
        PageInfo pageInfo = new PageInfo(select);
        pageInfo.setList(shopInfoByShopIds);
        return WrapMapper.ok(pageInfo);
    }

    //批量删除
    @PostMapping("/batchdelete")
    public Wrapper batchdelete(@RequestBody List<Long> ids) {
        //先测试仓库下面是否有店铺，或者仓库下面是否有物品
        List<Map> list = wmsWarehouseService.warehouseifnull(ids);
        int num = wmsWarehouseShopService.doit(ids);
        if (list.size() == 0 && num == 0) {
            wmsWarehouseService.beathdelete(ids);//删除warehouse表。删除warehouseshop表
            wmsWarehouseGroupService.batchDeletebywarehouseids(ids);
            return WrapMapper.ok("success");
        } else {
            return WrapMapper.error(ErrorCodeEnum.WMC100500018.msg());
        }
    }

    //获取所有的仓库
    @GetMapping("/searchit")
    public Wrapper<PageInfo> search(@ApiParam(name = "warehouseName", value = "组织id") @RequestParam(defaultValue = "") String warehouseName,
                                    @ApiParam(name = "warehouseId", value = "warehouseId") @RequestParam(defaultValue = "") Long warehouseId,
                                    @ApiParam(name = "runStatus", value = "类型") @RequestParam(defaultValue = "-1") Byte runStatus,
                                    @ApiParam(name = "regionProvinceId", value = "类型") @RequestParam(defaultValue = "-1") Long regionProvinceId,
                                    @ApiParam(name = "regionCityId", value = "类型") @RequestParam(defaultValue = "-1") Long regionCityId,
                                    @ApiParam(name = "regionCountyId", value = "类型") @RequestParam(defaultValue = "-1") Long regionCountyId,
                                    @ApiParam(name = "wareType", value = "仓库类型") @RequestParam(defaultValue = "-1") Byte wareType,
                                    @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size
    ) {
        PageHelper.startPage(page, size);
        WmsWarehouse wmsWarehouse = new WmsWarehouse();
        if (warehouseId!=null &&  warehouseId > 0) {
            wmsWarehouse.setWarehouseId(warehouseId);
        }

        if (warehouseName!=null&&!warehouseName.equals("")) {
            wmsWarehouse.setWarehouseName(warehouseName);
        }

        if (runStatus != -1 && runStatus != null) {
            wmsWarehouse.setRunStatus(runStatus);
        }

        if (regionProvinceId != -1 && regionProvinceId != null) {
            wmsWarehouse.setRegionProvinceId(regionProvinceId);
        }
        if (regionCityId !=  -1 && regionCityId != null) {
            wmsWarehouse.setRegionCityId(regionCityId);
        }
        if (regionCountyId != -1 && regionCountyId != null) {
            wmsWarehouse.setRegionCountyId(regionCountyId);
        }

        if (wareType != -1 && wareType != null) {
            wmsWarehouse.setWareType(wareType);
        }

        //获得groupId
        if(getGroupInfoDto().getGroupId()!=null && getGroupInfoDto().getGroupId()>1) {
            wmsWarehouse.setGroupId(getGroupInfoDto().getGroupId());

        }
        else{
            Wrapper<GroupInfoDto> groupInfoDto = uacUserFeignApi.getGroupInfoByGroupId(getGroupInfoDto().getGroupId());
            if (groupInfoDto != null && groupInfoDto.getCode() == 200){
                wmsWarehouse.setGroupId(groupInfoDto.getResult().getGroupId());

            }
        }

        List<WmsWarehouseDto> wmsWarehouseList = wmsWarehouseService.getWarehouseInfoList(wmsWarehouse);

        if (wmsWarehouseList.size() == 0) {
            List<WmsWarehouse> wmsWarehouses1 = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(wmsWarehouses1);
            return WrapMapper.ok(pageInfo);
        }

        PageInfo pageInfo = new PageInfo(wmsWarehouseList);

        return WrapMapper.ok(pageInfo);
    }

    @GetMapping("/findByPostion")
    public Wrapper findByPostion(@Param("latitude") Double latitude, @Param("longitude") Double longitude) {
        List<Map> list = wmsWarehouseService.findByPostion(latitude, longitude, maxDistance);
        return WrapMapper.ok(list);

    }

    @GetMapping("/getAllWarehouse")
    public Wrapper getalll(@ApiParam(name = "warehouseName", value = "仓库名称", defaultValue = "") @RequestParam(required = false) String warehouseName,
                           @ApiParam(name = "wareType", value = "仓库类型", defaultValue = "") @RequestParam(required = false) String wareType) {

        Example example = new Example(WmsWarehouse.class);
        Example.Criteria criteria = example.createCriteria();
        if (warehouseName != null) {
            criteria.andLike("warehouseName", '%' + warehouseName + '%');
        }
        if (wareType != null) {
            criteria.andEqualTo("wareType", wareType);
        }
        List<WmsWarehouse> wmsWarehouses = wmsWarehouseService.selectByExample(example);
        return WrapMapper.ok(wmsWarehouses);
    }


}
